package io.gitee.jinceon;

import io.gitee.jinceon.parser.SimpleTreeBaseVisitor;
import io.gitee.jinceon.parser.SimpleTreeParser;

import java.util.List;

public class SimpleTreeVisitor extends SimpleTreeBaseVisitor<String> {

    @Override
    public String visitParse(SimpleTreeParser.ParseContext ctx) {
        return visit(ctx.value());
    }

    @Override
    public String visitObject(SimpleTreeParser.ObjectContext ctx) {
        String key = ctx.label().getText();
        StringBuilder sb = new StringBuilder();
        sb.append("{").append(key).append(":[");
        List<SimpleTreeParser.ValueContext> values = ctx.collection().elements().value();
        for (int i = 0; i < values.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(visit(values.get(i)));
        }
        return sb.append("]}").toString();
    }

    @Override
    public String visitCollection(SimpleTreeParser.CollectionContext ctx) {
        StringBuilder result = new StringBuilder("[");
        List<SimpleTreeParser.ValueContext> values = ctx.elements().value();
        for (int i = 0; i < values.size(); i++) {
            if (i > 0) {
                result.append(",");
            }
            result.append(visit(values.get(i)));
        }
        result.append("]");
        return result.toString();
    }

    @Override
    public String visitStringLiteral(SimpleTreeParser.StringLiteralContext ctx) {
        return ctx.getText();
    }

    @Override
    public String visitValue(SimpleTreeParser.ValueContext ctx) {
        if (ctx.object() != null) {
            return visitObject(ctx.object());
        } else if (ctx.collection() != null) {
            return visitCollection(ctx.collection());
        } else {
            return visitStringLiteral(ctx.stringLiteral());
        }
    }

}

